﻿/*
Copyright (c) 2007-2011 William POTTIER - AllProgrammic

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
of the Software, and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Net.Sockets;
using System.Threading;
using NetAccess.Common.Exceptions;
using NetAccess.Common;

namespace NetAccess.Server
{
    public abstract partial class ServerLayer<T>
        where T : BaseServerConnexion
    {
        #region Fields
        /// <summary>
        /// Socket TCP pour les connexions entrantes
        /// </summary>
        private Socket _socketTCPService;
        /// <summary>
        /// Sémaphore pour l'arrivé des nouveaux clients
        /// </summary>
        private ManualResetEvent _waitTCPServiceIncommingConnexions;
        #endregion

        private void StartTCPService()
        {
            try
            {
                // Création du socket TCP : Utilisé pour les connexions entrantes des clients
                _socketTCPService = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socketTCPService.Bind(Configuration.TCPServiceEndPoint);

                // Start listen icomming connexions
                ThreadPool.QueueUserWorkItem(ListenTCPServiceIncommingConnexions);
            }
            catch (Exception ex)
            {
                State = ServerLayerState.Stopped;
                throw new NetAccessException(
                    "An error occured during starting TCPService. See InnerException for more informations", ex);
            }
        }

        private void StopTCPService()
        {
            // Stop listenning
            if (_socketTCPService != null)
                _socketTCPService.Shutdown(SocketShutdown.Both);

            // Stop resetEvent
            if (_waitTCPServiceIncommingConnexions != null)
                _waitTCPServiceIncommingConnexions.Close();

            _socketTCPService = null;
            _waitTCPServiceIncommingConnexions = null;
        }

        #region Incomming Client Manager
        private void ListenTCPServiceIncommingConnexions(object state)
        {
            // Value 5 for backlogs
            _socketTCPService.Listen(5);

            _waitTCPServiceIncommingConnexions = new ManualResetEvent(false);

            while (State == ServerLayerState.Starting || State == ServerLayerState.Started)
            {
                try
                {
                    _waitTCPServiceIncommingConnexions.Reset();

                    _socketTCPService.BeginAccept(CallbackTCPServiceIncommingConnexions, _socketTCPService);

                    _waitTCPServiceIncommingConnexions.WaitOne();
                }
                catch (NullReferenceException) { break; }
                catch (ObjectDisposedException) { break; }
            }
        }

        private void CallbackTCPServiceIncommingConnexions(IAsyncResult result)
        {
            Socket remote;

            try
            {
                remote = _socketTCPService.EndAccept(result);
            }
            catch (NullReferenceException) { return; }
            catch (ObjectDisposedException) { return; }
            catch (SocketException ex)
            {
                Logger.Instance.Error(ex);
                return;
            }


            try
            {
                // Start listening of a new client
                _waitTCPServiceIncommingConnexions.Set();
            }
            catch (NullReferenceException) { }
            catch (ObjectDisposedException) { }
            
            if (remote == null) return;

            var connexion = (T)Activator.CreateInstance(typeof(T));
            connexion.InternalInitialize(this, remote);
        }
        #endregion

    }
}
